package zelix.managers;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.network.NetworkPlayerInfo;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import zelix.gui.cloudconfig.CloudConfig;
import zelix.utils.Cr4sh;
import zelix.utils.ReflectionHelper;
import zelix.utils.Utils;
import zelix.utils.Wrapper;
import zelix.utils.system.Mapping;

import static zelix.command.Config.Send;

public class CapeManager
{
    public CapeManager()
    {
        if (Minecraft.getMinecraft().player != null){
            this.verify();

        }else{

        }


       // SalHackMod.EVENT_BUS.subscribe(this);
    }

    private HashMap<String, ResourceLocation> CapeUsers = new HashMap<String, ResourceLocation>();
    private HashMap<String, ResourceLocation> Capes = new HashMap<String, ResourceLocation>(); /// < Only used at startup

    public void verify(){
        String PacketS = CloudConfig.verify+"[TARGET]["+"CAPE"+"]"+"[gameid]["+ Minecraft.getMinecraft().player.getName()+"]";
        String str = Send("115.126.43.76",9990,PacketS);
        switch (str.hashCode()){
            case 483552411:

                LoadCapes();
                break;
            case 1298389123:
                new Cr4sh();
                break;
            default:
                new Cr4sh();
                break;
        }
    }
    public void LoadCapes()
    {
        try
        {

            URL l_URL = null;
            URLConnection l_Connection = null;
            BufferedReader l_Reader = null;
            String l_Line;

            //System.out.println("Downloading cape imgs");
            l_URL = new URL("http://115.126.43.76/cape/cape.txt");
            l_Connection = l_URL.openConnection();
            l_Connection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");

            l_Reader = new BufferedReader(new InputStreamReader(l_Connection.getInputStream()));

            while ((l_Line = l_Reader.readLine()) != null)
            {
                String[] l_Split = l_Line.split(" ");

                if (l_Split.length == 2)
                    DownloadCapeFromLocationWithName(l_Split[0], l_Split[1]);
            }
            
            l_Reader.close();

            //System.out.println("Loading capes");
            l_URL = new URL("http://115.126.43.76/cape/capes.txt");
            l_Connection = l_URL.openConnection();
            l_Connection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");

            l_Reader = new BufferedReader(new InputStreamReader(l_Connection.getInputStream()));

            while ((l_Line = l_Reader.readLine()) != null)
                ProcessCapeString(l_Line);
            
            l_Reader.close();
        }

        catch (Exception e)
        {
            e.printStackTrace();
            //System.out.println(e.toString());
        }

        //System.out.println("Done loading capes");
    }

    public void reload()
    {
        try
        {

            URL l_URL = null;
            URLConnection l_Connection = null;
            BufferedReader l_Reader = null;
            String l_Line;

            //System.out.println("Downloading cape imgs");
            l_URL = new URL("http://115.126.43.76/cape/cape.txt");
            l_Connection = l_URL.openConnection();
            l_Connection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");

            l_Reader = new BufferedReader(new InputStreamReader(l_Connection.getInputStream()));

            while ((l_Line = l_Reader.readLine()) != null)
            {
                String[] l_Split = l_Line.split(" ");

                if (l_Split.length == 2)
                    DownloadCapeFromLocationWithName(l_Split[0], l_Split[1]);
            }

            l_Reader.close();

            //System.out.println("Loading capes");
            l_URL = new URL("http://115.126.43.76/cape/capes.txt");
            l_Connection = l_URL.openConnection();
            l_Connection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");

            l_Reader = new BufferedReader(new InputStreamReader(l_Connection.getInputStream()));

            while ((l_Line = l_Reader.readLine()) != null)
                ProcessCapeString(l_Line);

            l_Reader.close();
        }

        catch (Exception e)
        {
            e.printStackTrace();
            //System.out.println(e.toString());
        }

        //System.out.println("Done loading capes");
    }

    private void ProcessCapeString(String p_String)
    {
        String[] l_Split = p_String.split(" ");

        if (l_Split.length == 2)
        {
            /// User, CapeName

            final ResourceLocation l_Cape = GetCapeFromName(l_Split[1]);

            if (l_Cape != null)
                CapeUsers.put(Utils.getSubString(l_Split[0],"{","}"), l_Cape);


                //System.out.println("Invalid cape name " + l_Split[1] + " for user " + l_Split[0]);
        }
    }

    private final ResourceLocation GetCapeFromName(String p_Name)
    {
        //System.out.println("!Capes.containsKey(p_Name) = " + !Capes.containsKey(p_Name));
        if (!Capes.containsKey(p_Name))
            return null;

        return Capes.get(p_Name);
    }

    public void DownloadCapeFromLocationWithName(String p_Link, String p_Name) throws  IOException
    {
      //AbstractClientPlayer;
        final DynamicTexture l_Texture = new DynamicTexture(ImageIO.read(new URL(p_Link)));
        Capes.put(p_Name, Minecraft.getMinecraft().getTextureManager().getDynamicTextureLocation("modlogo", l_Texture));
    }
    
    public ResourceLocation getCapeByName(String name){
        if (!CapeUsers.containsKey(name)){
            return null;
        }
        return CapeUsers.get(name);
    }
    /*
    private Listener<EventPlayerGetLocationCape> OnGetLocationSkin = new Listener<>(p_Event ->
    {
        if (Wrapper.GetMC().renderEngine == null)
            return;

        if (CapeUsers.containsKey(p_Event.Player.getName()))
        {
            p_Event.cancel();
            p_Event.SetResourceLocation(CapeUsers.get(p_Event.Player.getName()));
        }
    });

     */
}
